<?php

namespace App\Admin\Extensions\Tools;

use Encore\Admin\Admin;
use Encore\Admin\Form\Field\File;
use Encore\Admin\Grid\Tools\AbstractTool;
use Illuminate\Support\Facades\Request;

class ExcelImport extends AbstractTool
{
    protected $excel_file_name = '';
    protected $form_id = '';
    protected $upload_url = '';
    public function __construct($file_name = 'excel',$upload_url)
    {
            $this->excel_file_name =$file_name;
            $this->form_id = $file_name.'_form';
            $this->upload_url = $upload_url;
    }

    protected function script()
    {
        return <<<EOT
var excel_form = document.querySelector('#{$this->form_id}');
$('#{$this->form_id}_submit_btn').click(function(e){
$('#excel_import_modal')
var excel_data = new FormData(excel_form);
$.ajax({
url: '{$this->upload_url}',
type: 'post',
data: excel_data,
async: true,  
cache: false,  
contentType: false,  
processData: false,
success: function(data){
$.pjax.reload('#pjax-container');
//toastr.success(data);
}  
})
});

EOT;
    }

    public function render()
    {

        Admin::script($this->script());
        $file_input = (new File($this->excel_file_name,['上传Excel']))->render();
        return view('admin.tools.excel-import',['file_input_field'=>$file_input,'form_id'=>$this->form_id ]);
    }
}